package com.kun.util;

import com.kun.entity.JdContent;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 爬取京东数据
 *
 * @author kun.li
 */
@Component
public class JdJsoupParseUtil {


    @Value("${jd.thor:''}")
    private String thor;

    public List<JdContent> getJdContentList(String keyword) throws Exception {
        List<JdContent> jdContentList = new ArrayList<>();
        String url = String.format("https://search.jd.com/Search?keyword=%s", keyword);
        Document document = getDocument(url);
        Element element = document.getElementById("J_goodsList");
        Elements elements = element.getElementsByTag("li");
        for (Element element1 : elements) {
            String skuId = element1.attr("data-sku");
            String img = element1.getElementsByClass("p-img").get(0).getElementsByTag("img").attr("data-lazy-img");
            String price = element1.getElementsByClass("p-price").eq(0).get(0).getElementsByTag("strong").text();
            String name = element1.getElementsByClass("p-name p-name-type-2").eq(0).text();
            String shop = element1.getElementsByClass("p-shop").eq(0).text();
            JdContent jdContent = new JdContent();
            jdContent.setId(skuId);
            jdContent.setImg(img);
            jdContent.setPrice(price);
            jdContent.setName(name);
            jdContent.setShop(shop);
            jdContentList.add(jdContent);

        }
        return jdContentList;
    }

    public Document getDocument(String url) throws Exception {
        Map<String, String> cookies = new HashMap<>();
        // 使用UUID + 当前秒数
        String shshshfpx = UUID.randomUUID() + "-" + System.currentTimeMillis() / 1000;
        cookies.put("shshshfpx", shshshfpx);
        // thor 这个需要在京东网页中打开f12的Search的cookie中找到并复制
        cookies.put("thor", thor);
        return Jsoup.connect(url)
                .cookies(cookies)
                .get();
    }
}
